import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/common/widget/common_loading_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class PrimaryButton extends StatelessWidget {
  final String text;
  final VoidCallback? onPressed;
  final bool isLoading;
  final bool enable;

  // 新增自定义参数
  final double? width;
  final double? height;
  final double? borderRadius;
  final Color? textColor;
  final Color? backgroundColor;
  final Color? disabledColor;
  final TextStyle? textStyle;
  final EdgeInsetsGeometry? padding;

  const PrimaryButton({
    super.key,
    required this.text,
    this.onPressed,
    this.isLoading = false,
    this.enable = true,
    // 新增可定制参数
    this.width,
    this.height = 48,
    this.borderRadius = 6,
    this.textColor,
    this.backgroundColor,
    this.disabledColor,
    this.textStyle,
    this.padding,
  });

  @override
  Widget build(BuildContext context) {
    final isDisabled = !enable || isLoading || onPressed == null;
    final effectiveBgColor = isDisabled
        ? disabledColor ?? context.customColorThemeNonNull.disabledButtonBack
        : backgroundColor ?? context.colorScheme.primary;
    final effectiveTextColor = textColor ?? context.colorScheme.onPrimary;

    final button = ElevatedButton(
      style: ElevatedButton.styleFrom(
        minimumSize: Size(
          width != null ? width!.w : double.infinity, // 如果设置了宽度，使用指定宽度，否则占满
          height!.h,
        ),
        padding: padding,
        backgroundColor: effectiveBgColor,
        foregroundColor: effectiveTextColor,
        disabledBackgroundColor:
            disabledColor ?? context.customColorThemeNonNull.disabledButtonBack,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(borderRadius!.r), // 圆角设置
        ),
        elevation: 0, // 去除默认阴影
      ),
      onPressed: isDisabled ? null : onPressed,
      child: _buildChild(effectiveTextColor, context),
    );

    // 如果设置了宽度，使用 SizedBox 包裹以控制宽度
    if (width != null) {
      return SizedBox(
        width: width!.w,
        child: button,
      );
    }

    return button;
  }

  Widget _buildChild(Color textColor, BuildContext context) {
    // 构建文本样式：如果提供了 textStyle，使用它；否则使用默认样式
    final defaultStyle = context.textTheme.labelLarge?.copyWith(color: textColor);
    final effectiveStyle = textStyle ?? defaultStyle;
    
    if (isLoading) {
      return Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          SizedBox(
            width: 24.w,
            height: 24.h,
            child: const CommonLoadingWidget(),
          ),
          SizedBox(width: 10.w),
          Text(
            text,
            style: effectiveStyle,
          ),
        ],
      );
    }
    return Text(
      text,
      style: effectiveStyle,
    );
  }
}
